package de.fuberlin.inf.alp3.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This class is intended to simplify requesting user input.
 * @author stefanr
 *
 */
public class ConsoleInput {

    /**
     * This method helps reading in int values.
     * @param message The text to demand an input of an integer by the user.
     * @param errorMessage An error message if the conversion of the entered
     * text failed.
     * @return The entered number as int.
     */
    public static int readInt(String message, String errorMessage) {
        while (true) {
            try {
                return Integer.parseInt(ConsoleInput.readString(message));
            }
            catch (NumberFormatException exc) {
                System.out.println(errorMessage);
            }
        }
    }

    /**
     * This method helps reading in double values.
     * @param message The text to demand an input of an double by the user.
     * @param errorMessage An error message if the conversion of the entered
     * text failed.
     * @return The entered value as double.
     */
    public static double readDouble(String message, String errorMessage) {
        while (true) {
            try {
                return Double.parseDouble(ConsoleInput.readString(message));
            }
            catch (NumberFormatException exc) {
                System.out.println(errorMessage);
            }
        }
    }

    /**
     * This method helps reading in strings.
     * @param message The text to demand an input of an integer by the user.
     * @return The entered text as string.
     */
    public static String readString(String message) {
        String inputString = "";
        BufferedReader console = new BufferedReader(
                new InputStreamReader(System.in) );

        System.out.print(message + "\n> ");
        try {
            inputString = console.readLine();
        }
        catch (IOException exc) {
            exc.printStackTrace();
        }
        return inputString;
    }
    
    public static char readChar(String message)
    {
        char ch = 0;
        System.out.print(message + "\n> ");
        try {
            ch = (char) System.in.read();
            while ((char) System.in.read() != '\n');
        } catch (IOException exc) {
            exc.printStackTrace();
        }
        return ch;
    }

    public static boolean readBoolean(String message, String errorMessage) {
        while (true) {
            String input = ConsoleInput.readString(message);
            if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("1"))
                return true;
            else if (input.equalsIgnoreCase("false") || input.equalsIgnoreCase("no") || input.equalsIgnoreCase("0"))
                return false;
            else
                System.out.println(errorMessage);
        }
    }
}